#import "SlideCarrierView.h"
#import "AssetCollection.h"
//#import "ImageAsset.h"
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CAAnimation.h>
#import "ExtraCategories.h"

#define BORDER_CORNER_RADIUS    8.0

static NSSound *highlightSound = nil;

@implementation SlideCarrierView

+ (id)defaultAnimationForKey:(NSString *)key {
    static CABasicAnimation *basicAnimation = nil;

    // Example of overriding default animations: AppKit provides default animation specifications for "frameOrigin" and "frameCenterRotation", but in the WWDC Leopard seed the default animations for these properties are configured to use a simple linear progress curve (this might change for the final Leopard release).  We'd like to have a more interesting animation progress curve that has some acceleration and deceleration, so here we substitute our own CABasicAnimation with an "Ease In, Ease Out" CATimingFunction.
    if ([key isEqualToString:@"frameOrigin"] || [key isEqualToString:@"frameCenterRotation"]) {
        if (basicAnimation == nil) {
            basicAnimation = [[CABasicAnimation alloc] init];
            [basicAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        }
        return basicAnimation;
    } else {
        return [super defaultAnimationForKey:key];
    }
}

- initWithAsset:(Asset *)newAsset {
    self = [self initWithFrame:NSMakeRect(0, 0, 80, 80)];
    if (self) {
	asset = [newAsset retain];
    }
    [self setupRenderTimer];

	return self;
	
}

- (void)dealloc {
    [self setAsset:nil];
    [super dealloc];
}

- (Asset *)asset {
    return asset;
}

- (void)setAsset:(Asset *)newAsset {
    if (asset != newAsset) {
        id old = asset;
        asset = [newAsset retain];
        [old release];
    }
}
- (void) startHighlightTimer
{	
	mouseScrollX = 0.0;
	mouseScrollY = 0.0;
	[ self setupRenderTimer ];
}
- (void) killHighlightTimer
{
	
}
- (void)drawRect:(NSRect)rect {
		//NSLog(@"Draw");
	int lineThickness = 10;
	int sequenceXLeftOffset = 100;
	int sequenceXRightOffset = 30;

	NSRect boundary = [self bounds];
	NSPoint pt,center;
	
    pt = [[NSApp mainWindow] mouseLocationOutsideOfEventStream];
	pt = [self convertPoint:pt fromView:nil];
	
	center.x = boundary.origin.x + (boundary.size.width/2.0);
	center.y = boundary.origin.y + (boundary.size.height/2.0);
	
	
	//id transform = [NSAffineTransform transform];
	//id identity = [NSAffineTransform transform];
	
	NSBezierPath* dnaSequenceRect = [[[NSBezierPath alloc] init] autorelease];
	
	[dnaSequenceRect appendBezierPathWithRoundedRect:
		NSMakeRect(sequenceXLeftOffset, center.y-lineThickness/2.0 , boundary.size.width-sequenceXRightOffset, lineThickness) xRadius:1.0 yRadius:1.8];
	[dnaSequenceRect closePath];
	
	
	[dnaSequenceRect setLineJoinStyle:NSRoundLineJoinStyle];
	
	
	//NSLog(@"%f, %f",pt.x, pt.y);
	
	if ([dnaSequenceRect containsPoint:pt])
	{
		//[NCUTextView setSelectedRange:NSMakeRange(0,NCULength)];
		[dnaSequenceRect setLineWidth: 1.5];
	}
	else
		[dnaSequenceRect setLineWidth: 0.5];
	
	NSColor *newBackgroundColor = [NSColor colorWithCalibratedRed:.45 green:.43 blue:8.0 alpha: 1.0];
	NSGradient *newBackgroundGradient = [[NSGradient alloc]
										 initWithColorsAndLocations:
										 [NSColor whiteColor], 0.0, [NSColor whiteColor], 0.3, 
										 newBackgroundColor, 0.7, newBackgroundColor, 1.0,  
										 nil];
	
	
//	id myTransform = [[NSAffineTransform transform] mapFrom:[dnaSequenceRect bounds] to: NSMakeRect([dnaSequenceRect bounds].origin.x,[dnaSequenceRect bounds].origin.y*2,100,200)];
//	[dnaSequenceRect transformUsingAffineTransform:myTransform];
	NSPoint newGradientCenter = 
	[[[NSAffineTransform transform]
	  mapFrom:[dnaSequenceRect bounds] to: NSMakeRect(-20.0,-1.0,4.0,4.0)] transformPoint: center];
	[newBackgroundGradient drawInBezierPath: dnaSequenceRect relativeCenterPosition: newGradientCenter];
	[[NSColor blackColor] set];
	[dnaSequenceRect stroke];
	
	//[transform invert];
	//[transform concat];
	//					   topLineOffsetx+mouseScrollX, value - [self speed]/2.0 + mouseScrollY 
	//[transform translateXBy:topLineOffsetx+mouseScrollX - 100 yBy:value+5 - [self speed]/2.0 + mouseScrollY];
	//[transform concat];
	
	
    // Leave a transparent cutout behind our imageView.
    NSRect imageViewRect = [imageView frame];
    [[NSColor clearColor] set];
    NSRectFill(imageViewRect);
	
}
- (void) setupRenderTimer
{
	NSTimeInterval timeInterval = 1.0/6.0;
	
	myDrawTimer = [ [ NSTimer scheduledTimerWithTimeInterval:timeInterval
													  target:self
													selector:@selector( drawMe: )
													userInfo:nil repeats:YES ] retain ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSEventTrackingRunLoopMode ];
	[ [ NSRunLoop currentRunLoop ] addTimer:myDrawTimer
									forMode:NSModalPanelRunLoopMode ];
}

- (void) drawMe:(NSTimer *)timer;
{
	//NSLog(@"Drawing Me");
	[self display];
	//[self setNeedsDisplay:YES];
}
- (void)doHighlightEffect:(BOOL)highlight {
	
	NSRect boundary = [self bounds];
	NSPoint center,centerLoc;

	NSRect superFrame = [[self superview] frame];	
	
	//centerLoc.x = superFrame.origin.x + (superFrame.size.width/2.0);
	//centerLoc.y = superFrame.origin.y + (superFrame.size.height/2.0);
	//center.x = boundary.origin.x + (boundary.size.width/2.0);
	//center.y = boundary.origin.y + (boundary.size.height/2.0);

	//stunnachi	
	//frame.size.height = 100;
	
	
	//	[self setFrame:NSMakeRect(0 , centerLoc.y - (frame.size.height + 500)/2.0, frame.size.width , frame.size.height + 500)];
  

//	[self setBounds:NSMakeRect(0,0, 20, 90) ];
  //[self setFrameSize:NSMakeSize(50, 50)];
	
	
	NSArray *filters = nil;
    if (highlight) {
        // Instantiate the desired CIFilter, using the usual documented procedure for creating a CIFilter.
        
		CIFilter *filter = [CIFilter filterWithName:@"CIBloom"];
		[filter setDefaults];
		[filter setValue:[NSNumber numberWithFloat:20.0] forKey:@"inputRadius"];
		
		// name the filter so we can use the keypath to animate the inputIntensity
		// attribute of the filter
		[filter setName:@"pulseFilter"];
		
		
		
		
//		CIFilter *filter = [CIFilter filterWithName:@"CIPointillize"];
  //      [filter setDefaults];
    //    [filter setValue:[NSNumber numberWithFloat:4.0] forKey:@"inputRadius"];

        // A view's "contentFilters" property is an NSArray, allowing for CIFilters to be chained together to produce arbitrarily complex effects.  In this case we're just using a single filter, so we just need to wrap that single filter in an array.
        filters = [NSArray arrayWithObject:filter];
    } // Else, "filters" will be left as nil, and setContentFilters: below will remove the view's previously assigned contentFilters.

    // When applying the highlight effect (highlight == YES), we want the change in appearance to take effect immediately.  When unhighlighting (highlight == NO), however, we'd like for the removal of the filter effect to fade out gradually instead of being instantaneous.  There are two ways you can apply such a change without animating.  One is to set the enclosing NSAnimationContext's "duration" to zero, as we do below when "highlight" is true.  Another would be to message the view directly to make the contentFilters change, rather than messaging through the view's animator.  Doing "[self setContentFilters:filters]" (as with setting any other view property directly, without going through the animator) always has an instantaneous effect, regardless of the enclosing NSAnimationContext's duration.
    [NSAnimationContext beginGrouping];
    [[NSAnimationContext currentContext] setDuration:highlight ? 0.0 : 0.5];
    [[self animator] setContentFilters:filters];
    [NSAnimationContext endGrouping];

    // Just for fun, play a sound when highlighting, to give a little bit of feedback.
    if (highlight) {
        if (highlightSound == nil) {
            highlightSound = [[NSSound soundNamed:@"Morse"] retain];
        }
        [highlightSound play];
    }
}

// Just to show off the use of Core Image filters to apply effect to a view's content, highlight the SlideCarrierView on mouseDown:, and unhighlight it on mouseUp:
- (void)mouseDown:(NSEvent *)theEvent {
    [self doHighlightEffect:YES];
}

- (void)mouseUp:(NSEvent *)theEvent {
    [self doHighlightEffect:NO];
}

@end
